﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using CSRedis;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base
{
    public partial class Base_UnitItemsBusiness : BaseBusiness<Base_UnitItems>, IBase_UnitItemsBusiness, ITransientDependency
    {
        private static CSRedisClient RediC;
        public Base_UnitItemsBusiness(IDbAccessor db)
            : base(db)
        {
        }

        #region 外部接口

        public async Task<PageResult<Base_UnitItems>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_UnitItems>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_UnitItems, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Base_UnitItems> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        //[DataAddLog(UserLogType.计量单位, "Name", "计量单位")]
        //[DataRepeatValidate(new string[] {  "Name" }, new string[] {"计量单位名称" })]
        public async Task AddDataAsync(Base_UnitItems data, RedisOptions _redisOptions)
        {
            Dictionary<string, string> TagSet;
            _redisOptions.DbChannel = (int)Redis_Type.redis8;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            if (RedisSetHelper.Exists("BaseUnitGroupRedis"))
            {
                RedisSetHelper.KeyDelete("BaseUnitGroupRedis");
            }

            //判断是否重复
            if (!string.IsNullOrEmpty(data.Name))
            {
               var dataLength=  Db.GetListBySql<Base_UnitItems>(" SELECT * FROM  Base_UnitItems where GroupId = '" + data.GroupId + "' AND `Name`= '"+ data.Name + "'");
                if (dataLength.Count > 0)
                {
                    throw new Exception("计量单位名称不可重复在同一单位组下！");
                }
                else {
                    var dataLengthInfo = Db.GetListBySql<Base_UnitItems>(" SELECT * FROM  Base_UnitItems where GroupId = '" + data.GroupId + "' AND `Code`= '" + data.Code + "'");
                    if (dataLengthInfo.Count > 0)
                    {
                        throw new Exception("计量单位编码不可重复在同一单位组下！");
                    }
                }
            }
            //判断当前数据状态是true
            if (data.IsDefault)
            {
                //批量修改分组下所有数据记录的状态为false
                await ExecuteSqlAsync("update Base_UnitItems SET IsDefault=0 where GroupId='" + data.GroupId + "'");
            }
            //插入新数据
            await InsertAsync(data);
            if (RedisSetHelper.Exists("BaseUnitGroupRedis"))
            {
                var rs = RediC.HGetAll("BaseUnitGroupRedis");
                if (rs == null && rs.Keys.Count() == 0)
                {
                    var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                    TagSet = new Dictionary<string, string>();
                    foreach (var item in UnitGroup)
                    {
                        TagSet.Add(item.Id, item.Name);//
                    }
                    RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);
                }
            }
            else
            {
                var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                TagSet = new Dictionary<string, string>();
                foreach (var item in UnitGroup)
                {
                    TagSet.Add(item.Id, item.Name);//
                }
                RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);
            }
        }

        //[DataEditLog(UserLogType.计量单位, "Name", "计量单位")]
        //[DataRepeatValidate(new string[] { "Code", "Name" }, new string[] { "计量单位编码", "计量单位名称" })]
        public async Task UpdateDataAsync(Base_UnitItems data, RedisOptions _redisOptions)
        {
            //判断是否重复
            if (!string.IsNullOrEmpty(data.Name))
            {
                var dataLength = Db.GetListBySql<Base_UnitItems>(" SELECT * FROM  Base_UnitItems where GroupId = '" + data.GroupId + "' AND `Name`= '" + data.Name + "' AND Id!='"+data.Id+"'");
                if (dataLength.Count > 0)
                {
                    throw new Exception("计量单位不可重复在同一单位组下！");
                }
                else {
                    var dataLengthInfo = Db.GetListBySql<Base_UnitItems>("SELECT * FROM  Base_UnitItems where GroupId = '" + data.GroupId + "' AND `Code`= '" + data.Code + "' AND Id!='" + data.Id + "'");
                    if (dataLengthInfo.Count > 0)
                    {
                        throw new Exception("计量单位编码不可重复在同一单位组下！");
                    }
                }
            }
            _redisOptions.DbChannel = (int)Redis_Type.redis8;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            RedisSetHelper.KeyDelete("BaseUnitGroupRedis");
            //判断当前数据状态是true
            if (data.IsDefault)
            {
                //批量修改分组下所有数据记录的状态为false
                await ExecuteSqlAsync("update Base_UnitItems SET IsDefault=0 where GroupId='" + data.GroupId + "'");
            }
            await UpdateAsync(data);
            Dictionary<string, string> TagSet;

            if (RedisSetHelper.Exists("BaseUnitGroupRedis"))
            {
                var rs = RediC.HGetAll("BaseUnitGroupRedis");
                if (rs == null && rs.Count() == 0)
                {
                    var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                    TagSet = new Dictionary<string, string>();
                    foreach (var item in UnitGroup)
                    {
                        TagSet.Add(item.Id, item.Name);//
                    }
                    RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);
                }
            }
            else
            {
                var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                TagSet = new Dictionary<string, string>();
                foreach (var item in UnitGroup)
                {
                    TagSet.Add(item.Id, item.Name);//
                }
                RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);

            }
        }

        [DataDeleteLog(UserLogType.计量单位, "Name", "计量单位")]
        public async Task DeleteDataAsync(List<string> ids)
        {
            var materialList = await Db.GetListBySqlAsync<PB_Material>("select * from pb_material where (storageId like '%"+ ids + "%' or saleId like '%" + ids + "%' or purchaseId like '%" + ids + "%' or productionId like '%" + ids + "%') ");
            if (materialList.Count > 0)
            {
                throw new BusException("计量单位已备引用不能删除");
            }

            new RedisOptions().DbChannel = 8;
            RedisSetHelper redis = new RedisSetHelper(new RedisOptions());
            RedisSetHelper.KeyDelete("BaseUnitGroupRedis");
            await DeleteAsync(ids);
            Dictionary<string, string> TagSet;
            if (RedisSetHelper.Exists("BaseUnitGroupRedis"))
            {
                var rs = RediC.HGetAll("BaseUnitGroupRedis");
                if (rs == null && rs.Keys.Count() == 0)
                {
                    var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                    TagSet = new Dictionary<string, string>();
                    foreach (var item in UnitGroup)
                    {
                        TagSet.Add(item.Id, item.Name);//
                    }
                    RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);
                }
            }
            else
            {
                var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                TagSet = new Dictionary<string, string>();
                foreach (var item in UnitGroup)
                {
                    TagSet.Add(item.Id, item.Name);//
                }
                RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);

            }
        }

        public async Task<List<Base_UnitItemsDTO>> GetDataListAsyncs(string GroupId)
        {
            //var q = GetIQueryable();
            //q = q.Where(w => w.WorkStationid == WorkStationid);

            //return await q.ToListAsync();
            Expression<Func<Base_UnitItems, Base_UnitGroup, Base_UnitItemsDTO>> select = (a, b) => new Base_UnitItemsDTO
            {
                GroupName = b.Name,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_UnitGroup>() on a.GroupId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            //筛选
            if (!GroupId.IsNullOrEmpty())
            {
                q = q.Where(w => w.GroupId == GroupId);
            }
            var res = await q.ToListAsync();

            return res;
        }

        public async Task<List<Base_UnitItemsDTO>> GetDataListGroupAsync(string GroupId)
        {
            //var q = GetIQueryable();
            //q = q.Where(w => w.WorkStationid == WorkStationid);

            //return await q.ToListAsync();
            Expression<Func<Base_UnitItems, Base_UnitGroup, Base_UnitItemsDTO>> select = (a, b) => new Base_UnitItemsDTO
            {
                GroupName = b.Name,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_UnitGroup>() on a.GroupId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            //筛选
            if (!GroupId.IsNullOrEmpty())
            {
                q = q.Where(w => w.GroupId == GroupId);
            }
            var res = await q.ToListAsync();

            return res;
        }

        public async Task<PageResult<Base_UnitItems>> GetDataGroupListAsync(PageInput<ConditionDTO> input, string GroupId)
        {
            var q = GetIQueryable().Where(S => S.GroupId == GroupId);
            var where = LinqHelper.True<Base_UnitItems>();
            var search = input.Search;

            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_UnitItems, bool>(
                    ParsingConfig.Default, false, $@"Code.Contains(@0) or Name.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }



        #endregion

        #region 私有成员

        #endregion
    }
}